package com.denso.store.store;

import com.denso.store.admin.administrator.AdminService;
import com.denso.store.admin.scheduler.SchedulerService;
import com.denso.store.common.Status;
import com.denso.store.common.Tools;
import com.denso.store.common.model.Admin;
import com.denso.store.common.model.Scheduler;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.xiaoleilu.hutool.http.HttpUtil;

import java.util.Date;
import java.util.List;

/**
 * Created by lijian on 2017/10/29.
 */
public class StoreController extends Controller {

    private static SchedulerService service = new SchedulerService();

    public void index() {
        List<Scheduler> schedulerList = service.findActive();
        setAttr("schedulerList", schedulerList);
        render("index.html");
    }

    public void pass() {
        int id = getParaToInt("id");
        Scheduler scheduler = service.findById(id);
        scheduler.setStatus(Status.PASS);
        scheduler.update();

        callGuard();

        index();
    }

    public void modify() {
        int id = getParaToInt("id");
        SchedulerService schedulerService = new SchedulerService();
        Scheduler scheduler = schedulerService.findById(id);

        setAttr("scheduler", scheduler);
        render("modify.html");
    }

    public void update() {
        Scheduler scheduler = getModel(Scheduler.class);

        int hour = getParaToInt("hour");
        int minute = getParaToInt("minute");
        Date planTime = Tools.convertDate(hour, minute);
        scheduler.setPlanTime(planTime);

        String name = getPara("name");
        String password = getPara("password");

        AdminService adminService = new AdminService();
        Admin admin = adminService.login(1, name, password);
        if(admin == null) {
            // 库管员身份校验失败
            setAttr("notice", "管理员身份校验失败");
            setAttr("scheduler", scheduler);
            render("modify.html");
        } else {
            // 库管员身份校验成功,更新计划
            scheduler.update();
            setAttr("notice", "计划修改成功");
            index();
        }
    }

    private void callGuard() {
        new Thread() {
            public void run() {
                String guardUrl = PropKit.get("guardUrl");
                String result = HttpUtil.get(guardUrl);
            }
        }.start();
    }

}
